import React from 'react';
import {Link} from 'react-router-dom';

import {FeatureBadge} from '@sentry/scraps/badge/featureBadge';
import {Button} from '@sentry/scraps/button';
import {Flex} from '@sentry/scraps/layout';
import {Text} from '@sentry/scraps/text';

import {Breadcrumbs, type Crumb} from 'sentry/components/breadcrumbs';
import ConfirmDelete from 'sentry/components/confirmDelete';
import DropdownButton from 'sentry/components/dropdownButton';
import {DropdownMenu, type MenuItemProps} from 'sentry/components/dropdownMenu';
import FeedbackButton from 'sentry/components/feedbackButton/feedbackButton';
import IdBadge from 'sentry/components/idBadge';
import * as Layout from 'sentry/components/layouts/thirds';
import Version from 'sentry/components/version';
import {
  IconDelete,
  IconDownload,
  IconEllipsis,
  IconRefresh,
  IconTelescope,
} from 'sentry/icons';
import {t} from 'sentry/locale';
import ProjectsStore from 'sentry/stores/projectsStore';
import {trackAnalytics} from 'sentry/utils/analytics';
import type {UseApiQueryResult} from 'sentry/utils/queryClient';
import type RequestError from 'sentry/utils/requestError/requestError';
import {useIsSentryEmployee} from 'sentry/utils/useIsSentryEmployee';
import useOrganization from 'sentry/utils/useOrganization';
import type {BuildDetailsApiResponse} from 'sentry/views/preprod/types/buildDetailsTypes';
import {makeReleasesUrl} from 'sentry/views/preprod/utils/releasesUrl';

import {useBuildDetailsActions} from './useBuildDetailsActions';

interface BuildDetailsHeaderContentProps {
  artifactId: string;
  buildDetailsQuery: UseApiQueryResult<BuildDetailsApiResponse, RequestError>;
  projectId: string;
  projectType: string | null;
}

export function BuildDetailsHeaderContent(props: BuildDetailsHeaderContentProps) {
  const organization = useOrganization();
  const isSentryEmployee = useIsSentryEmployee();
  const {buildDetailsQuery, projectId, artifactId, projectType} = props;
  const {
    isDeletingArtifact,
    handleDeleteArtifact,
    handleRerunAction,
    handleDownloadAction,
  } = useBuildDetailsActions({
    projectId,
    artifactId,
  });

  const {
    data: buildDetailsData,
    isPending: isBuildDetailsPending,
    isError: isBuildDetailsError,
  } = buildDetailsQuery;

  // TODO(preprod): for now show nothing for loading/error states, but in the future we
  // might be able to show the release breadcrumb
  if (isBuildDetailsPending) {
    return (
      <Flex direction="column" padding="0 0 xl 0">
        {/* Empty header space - no skeleton content */}
      </Flex>
    );
  }

  if (isBuildDetailsError || !buildDetailsData) {
    return (
      <Flex direction="column" padding="0 0 xl 0">
        {/* Empty header space during error */}
      </Flex>
    );
  }

  const project = ProjectsStore.getBySlug(projectId);

  const breadcrumbs: Crumb[] = [
    {
      to: makeReleasesUrl(project?.id, {
        appId: buildDetailsData.app_info.app_id ?? undefined,
      }),
      label: 'Releases',
    },
  ];

  if (buildDetailsData.app_info.version) {
    breadcrumbs.push({
      to: makeReleasesUrl(project?.id, {
        version: buildDetailsData.app_info.version,
        appId: buildDetailsData.app_info.app_id ?? undefined,
      }),
      label: buildDetailsData.app_info.version,
    });
  }

  breadcrumbs.push({
    label: 'Build Details',
  });

  const version = `v${buildDetailsData.app_info.version ?? 'Unknown'} (${buildDetailsData.app_info.build_number ?? 'Unknown'})`;

  const handleCompareClick = () => {
    trackAnalytics('preprod.builds.details.compare_build_clicked', {
      organization,
      platform: buildDetailsData.app_info?.platform ?? null,
      build_id: buildDetailsData.id,
      project_type: projectType,
      project_slug: projectId,
    });
  };

  const handleConfirmDelete = () => {
    handleDeleteArtifact();
    trackAnalytics('preprod.builds.details.delete_build', {
      organization,
      platform: buildDetailsData.app_info?.platform ?? null,
      build_id: buildDetailsData.id,
      project_slug: projectId,
      project_type: projectType,
    });
  };

  return (
    <React.Fragment>
      <Layout.HeaderContent>
        <Flex align="center" gap="sm">
          <Breadcrumbs crumbs={breadcrumbs} />
          <FeatureBadge type="beta" />
        </Flex>
        <Layout.Title>
          {project && <IdBadge project={project} avatarSize={28} hideName />}
          <Version version={version} anchor={false} truncate />
        </Layout.Title>
      </Layout.HeaderContent>

      <Layout.HeaderActions>
        <Flex align="center" gap="sm" flexShrink={0}>
          <FeedbackButton
            feedbackOptions={{
              tags: {
                'feedback.source': 'preprod.buildDetails',
              },
            }}
          />
          <Link
            to={`/organizations/${organization.slug}/preprod/${projectId}/compare/${buildDetailsData.id}/`}
            onClick={handleCompareClick}
          >
            <Button size="sm" priority="default" icon={<IconTelescope />}>
              {t('Compare Build')}
            </Button>
          </Link>
          <ConfirmDelete
            message={t(
              'Are you sure you want to delete this build? This action cannot be undone and will permanently remove all associated files and data.'
            )}
            confirmInput={artifactId}
            onConfirm={handleConfirmDelete}
          >
            {({open: openDeleteModal}) => {
              const menuItems: MenuItemProps[] = [
                {
                  key: 'delete',
                  label: (
                    <Flex align="center" gap="sm">
                      <IconDelete size="sm" color="danger" />
                      <Text variant="danger">{t('Delete Build')}</Text>
                    </Flex>
                  ),
                  onAction: openDeleteModal,
                  textValue: t('Delete Build'),
                },
              ];

              if (isSentryEmployee) {
                menuItems.push({
                  key: 'admin-section',
                  label: t('Admin (Sentry Employees only)'),
                  children: [
                    {
                      key: 'rerun',
                      label: (
                        <Flex align="center" gap="sm">
                          <IconRefresh size="sm" />
                          {t('Rerun Analysis')}
                        </Flex>
                      ),
                      onAction: handleRerunAction,
                      textValue: t('Rerun Analysis'),
                    },
                    {
                      key: 'download',
                      label: (
                        <Flex align="center" gap="sm">
                          <IconDownload size="sm" />
                          {t('Download Build')}
                        </Flex>
                      ),
                      onAction: handleDownloadAction,
                      textValue: t('Download Build'),
                    },
                  ],
                });
              }

              return (
                <DropdownMenu
                  items={menuItems}
                  trigger={(triggerProps, _isOpen) => (
                    <DropdownButton
                      {...triggerProps}
                      size="sm"
                      aria-label="More actions"
                      showChevron={false}
                      disabled={isDeletingArtifact || !artifactId}
                    >
                      <IconEllipsis />
                    </DropdownButton>
                  )}
                />
              );
            }}
          </ConfirmDelete>
        </Flex>
      </Layout.HeaderActions>
    </React.Fragment>
  );
}
